package com.cadre.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cadre.common.utils.R;
import com.cadre.common.utils.ZipUtil;
import com.cadre.common.utils.common.GenerateUUID;
import com.cadre.common.utils.oldutil.*;
import com.cadre.system.domain.officer.B01;
import com.cadre.system.domain.officer.BatchconferenceEntity;
import com.cadre.system.mapper.B01Mapper;
import com.cadre.system.mapper.BatchconferenceMapper;
import com.cadre.system.service.DataStreamService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.*;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.*;
import java.util.regex.Pattern;

@Service("DataStreamService")
public class DataStreamServiceImpl extends ServiceImpl<BatchconferenceMapper, BatchconferenceEntity> implements DataStreamService {
    @Autowired
    StreamConfig streamconfig;
    @Autowired
    B01Mapper b01Mapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Value("${spring.datasource.druid.master.username}")
    private String username;

    @Override
    public R createZip(Map<String, String> map, HttpServletResponse response) {
        if (map.get("unitid").equals("")) {
            return R.ok().put("mess", (Object) "未选择单位");
        }
        String unitid = map.get("unitid");
        String path = this.streamconfig.getFile() + RandomUtil.getRandom() + "/";
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String db = path + "export.db";
        DataSource drs = this.jdbcTemplate.getDataSource();
        B01 b01 = (B01) this.b01Mapper.selectById(unitid);
        try {
            new DataSyncUtil().dbSync(new J4SqlLiteUtils().getConnection(db), drs.getConnection(), this.streamconfig, this.username, unitid, map);
            dataEncryption(path, "export.db", b01.getB0101(), b01.getFlowid());
            String data = new SimpleDateFormat("yyyy.MM.dd").format(new Date());
            new ZipUtil(path + "\\数据上报[" + data + "].zip", path + "result\\").zip();
            WordUtils.toDownload(new File(path + "\\数据上报[" + data + "].zip"), response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("mess", (Object) "生成成功");
    }

    private void dataEncryption(String path, String fileName, String unitName, String unitid) {
        try {
            byte[] pwdbytes = new DesUtilForDataStream().encrypt1(EncryptUtil.genRandomNum(Integer.parseInt(this.streamconfig.getLiblength())));
            String pwd = DesUtilForDataStream.GetBase64Str(pwdbytes);
            String newpath = path + "\\result\\";
            File dir = new File(newpath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File encryptFile = new File(newpath + "\\CadreEncrypt.lib");
            new TextUtil(path, encryptFile);
            TextUtil.creatTxtFile();
            System.out.println("提示：lib文件已经创建！");
            TextUtil.writeTxtFile(pwd);
            System.out.println("提示：lib文件已写入完毕！");
            System.out.println("提示：数据库加密开始！");
            copyFile(path + fileName, newpath + fileName, pwdbytes);
            File txtFile = new File(newpath + "\\unit.txt");
            new TextUtil(path, encryptFile);
            TextUtil.creatTxtFile();
            FileOutputStream fileOutputStream = new FileOutputStream(txtFile);
            fileOutputStream.write((unitName + "\n" + unitid).getBytes());
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean copyFile(String oldPath$Name, String newPath$Name, byte[] bytes) {
        try {
            File oldFile = new File(oldPath$Name);
            if (!oldFile.exists()) {
                System.out.println("--Method--:copyFile:  oldFile not exist.");
                return false;
            } else if (!oldFile.isFile()) {
                System.out.println("--Method--:copyFile:  oldFile not file.");
                return false;
            } else if (!oldFile.canRead()) {
                System.out.println("--Method--:copyFile:  oldFile cannot read.");
                return false;
            } else {
                FileInputStream fileInputStream = new FileInputStream(oldPath$Name);
                FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
                byte[] buffer = new byte[1024];
                fileOutputStream.write(bytes);
                while (true) {
                    int byteRead = fileInputStream.read(buffer);
                    if (-1 != byteRead) {
                        fileOutputStream.write(buffer, 0, byteRead);
                    } else {
                        fileInputStream.close();
                        fileOutputStream.flush();
                        fileOutputStream.close();
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public R impZip(MultipartFile file) {
        String path = this.streamconfig.getFile() + RandomUtil.getRandom() + "\\";
        List<Map<String, Object>> listSqllite = new ArrayList<>();
        System.out.println("上传文件存放目录>>>>" + path);
        File fileLocal = new File(path + "\\" + file.getName());
        String abc = "";
        new DesUtilForDataStream();
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), fileLocal);
            ZipUtil.unzip(path + "/" + file.getName());
            String str = ReadTxtFromSDCard(path + "/result/CadreEncrypt.lib");
            String[] arr = readTxt(path + "/result/unit.txt").split("\n");
            System.out.println("<<<<<<<<<<<<<<<<");
            for (String str2 : arr) {
                System.out.println(str2);
            }
            byte[] pwsbyte = Base64.decodeBase64(str);
            String connPath = path + "/result/import.db";
            recoveryFile(path + "/result/export.db", connPath, pwsbyte);
            System.out.println("生成本地文件>>>>" + path);
            listSqllite = getRepeatData(connPath);
            abc = DesUtilForDataStream.encrypt2(connPath, DesUtilForDataStream.DEFAULT_KEY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("list", (Object) listSqllite).put("connpath", (Object) abc).put("unitName", (Object) "");
    }

    private List<Map<String, Object>> getList(ResultSet rs) {
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                for (int i = 0; i < columnCount; i++) {
                    String columnName = metaData.getColumnName(i + 1);
                    map.put(columnName, rs.getString(columnName));
                }
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    private List<Map<String, Object>> getRepeatData(String connPath) {
        List<Map<String, Object>> listSqllite = new ArrayList<>();
        try {
            ResultSet rs = new J4SqlLiteUtils().getConnection(connPath).createStatement().executeQuery("select a0101,A0105,datetime(A0106) A0106,A0183 from A01");
            System.out.println("姓名\t性别\t年龄\t");
            listSqllite = getList(rs);
            ResultSet rs2 = this.jdbcTemplate.getDataSource().getConnection().createStatement().executeQuery("select a0101,A0105,to_char( A0106,'yyyy-MM-dd HH24:mi:ss') A0106,A0183 from A01");
            List<Map<String, Object>> list1 = getList(rs2);
            rs2.close();
            listSqllite.retainAll(list1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listSqllite;
    }

    private List<Map<String, Object>> getRepeatData_N(String connPath) {
        List<Map<String, Object>> listSqllite = new ArrayList<>();
        try {
            ResultSet rs = new J4SqlLiteUtils().getConnection(connPath).createStatement().executeQuery("select a0101,A0105,datetime(A0106) A0106,A0183 from A01");
            System.out.println("姓名\t性别\t年龄\t");
            listSqllite = getList(rs);
            ResultSet rs2 = this.jdbcTemplate.getDataSource().getConnection().createStatement().executeQuery("select a0101,A0105,to_char( A0106,'yyyy-MM-dd HH24:mi:ss') A0106,A0183 from A01");
            List<Map<String, Object>> list1 = getList(rs2);
            rs2.close();
            listSqllite.removeAll(list1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listSqllite;
    }

    public static boolean recoveryFile(String oldPath$Name, String newPath$Name, byte[] bytes) {
        try {
            File oldFile = new File(oldPath$Name);
            if (!oldFile.exists()) {
                System.out.println("--Method--:copyFile:  oldFile not exist.");
                return false;
            } else if (!oldFile.isFile()) {
                System.out.println("--Method--:copyFile:  oldFile not file.");
                return false;
            } else if (!oldFile.canRead()) {
                System.out.println("--Method--:copyFile:  oldFile cannot read.");
                return false;
            } else {
                FileInputStream fileInputStream = new FileInputStream(oldPath$Name);
                FileOutputStream fileOutputStream = new FileOutputStream(newPath$Name);
                byte[] buffer = new byte[bytes.length];
                while (true) {
                    int byteRead = fileInputStream.read(buffer);
                    if (-1 == byteRead) {
                        fileInputStream.close();
                        fileOutputStream.flush();
                        fileOutputStream.close();
                        return true;
                    } else if (!Arrays.equals(buffer, bytes)) {
                        fileOutputStream.write(buffer, 0, byteRead);
                    } else {
                        System.out.println("相同数据");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private static String ReadTxtFromSDCard(String filename) {
        StringBuilder sb = new StringBuilder("");
        try {
            FileInputStream input = new FileInputStream(filename);
            byte[] temp = new byte[1024];
            while (true) {
                int len = input.read(temp);
                if (len <= 0) {
                    break;
                }
                sb.append(new String(temp, 0, len));
            }
            input.close();
        } catch (IOException e) {
            System.out.println("ReadTxtFromSDCard");
            e.printStackTrace();
        }
        return sb.toString();
    }

    private List<Map<String, Object>> getAllList(String connPath) {
        List<Map<String, Object>> listSqllite = new ArrayList<>();
        try {
            ResultSet rs = new J4SqlLiteUtils().getConnection(connPath).createStatement().executeQuery("select a0101,A0105,datetime(A0106) A0106,A0183 from A01");
            System.out.println("姓名\t性别\t年龄\t");
            listSqllite = getList(rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listSqllite;
    }

    @Override
    public void exportDate(Map<String, Object> params, String toUserId) {
        seedMess("导入开始", toUserId);
        String type = params.get("type").toString();
        String exportType = params.get("exportType").toString();
        String unitid = params.get("unitid").toString();
        String connpath = params.get("connpath").toString();
        new DesUtilForDataStream();
        try {
            connpath = DesUtilForDataStream.decrypt2(connpath, DesUtilForDataStream.DEFAULT_KEY);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        System.out.println("获取解密后路径>>>" + connpath);
        String path = new File(connpath).getParent();
        System.out.println(path);
        String[] arr = readTxt(path + "/unit.txt").split("\n");
        seedMess("读取配置文件", toUserId);
        String importUnitid = "";
        String name = "";
        if (arr.length >= 1) {
            name = arr[0];
        }
        if (arr.length >= 2) {
            importUnitid = arr[1];
        }
        if (importUnitid.equals("")) {
            seedMess("导入的单位id未能获取", toUserId);
        }
        if (name.equals("")) {
            seedMess("导入的单位名称", toUserId);
        }
        sourceDateHandle(type, unitid, importUnitid, connpath, toUserId);
        seedMess("预处理数据开始", toUserId);
        transferDate(connpath, exportType, toUserId);
        seedMess("导入数据开始", toUserId);
    }

    private void transferDate(String dbPath, String exportType, String toUserId) {
        J4SqlLiteUtils j = new J4SqlLiteUtils();
        DataSource drs = this.jdbcTemplate.getDataSource();
        try {
            Connection sqlliteConn = j.getConnection(dbPath);
            Connection oracleConn = drs.getConnection();
            List<Map<String, Object>> listAll = new ArrayList<>();
            Collections.addAll(new ArrayList<>(), this.streamconfig.getTables().split(","));
            if (exportType.equals("1")) {
                seedMess("人员信息导入规则>>重复人员信息不导入", toUserId);
                seedMess("人员信息表格数据>>获取重复记录", toUserId);
                listAll = getRepeatData_N(dbPath);
            } else if (exportType.equals("2")) {
                seedMess("人员信息导入规则>>覆盖库中人员", toUserId);
                seedMess("人员信息表格数据>>获取重复记录", toUserId);
                List<Map<String, Object>> list = getRepeatData(dbPath);
                seedMess("人员信息表格数据>>清理导入的重复记录", toUserId);
                deleteRepeatData(list, oracleConn, "oracle");
                listAll = getAllList(dbPath);
            } else if (exportType.equals("3")) {
                seedMess("人员信息导入规则>>新增导入", toUserId);
                seedMess("将接收所有数据时间会长一点请耐心等待", toUserId);
                listAll = getAllList(dbPath);
            }
            seedMess("先插入单位相关的表>>开始", toUserId);
            insertBunit(dbPath, toUserId);
            if (listAll.size() > 0) {
                seedMess("将插入" + listAll.size() + "信息", toUserId);
                insertPerson(dbPath, toUserId, listAll);
            }
            seedMess("插入人员相关的表>>开始", toUserId);
            sqlliteConn.close();
            oracleConn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void insertPerson(String dbPath, String toUserId, List<Map<String, Object>> listAll) {
        DataSource drs = this.jdbcTemplate.getDataSource();
        String[] tableArry = this.streamconfig.getTables().split(",");
        List<String> list_table_names = new ArrayList<>();
        Collections.addAll(list_table_names, tableArry);
        list_table_names.add("A01");
        try {
            Connection oracleConn = drs.getConnection();
            Connection sqlliteConn = new J4SqlLiteUtils().getConnection(dbPath);
            seedMess("获取人员相关所有建表语句>>开始", toUserId);
            Map<String, String> createTableMap = getCreateTableSql(oracleConn, list_table_names);
            seedMess("获取人员相关所有建表语句>>结束", toUserId);
            seedMess("获取人员表字段信息>>开始", toUserId);
            Map<String, Map<String, String>> map = null;
            seedMess("获取人员表字段信息>>结束", toUserId);
            Statement stmt1 = sqlliteConn.createStatement();
            Statement stmt2 = sqlliteConn.createStatement();
            String oldId = null;
            StringBuffer sqlBuf = new StringBuffer();
            String insertStr1 = null;
            String insertStr2 = null;
            String preSQL = null;
            String createTableSql = null;
            String[] insertArr = null;
            Map<String, String> MapA01 = null;
            for (int n = 0; n < listAll.size(); n++) {
                if (listAll.get(n).get("A0101") != null) {
                    sqlBuf.append("select * from A01 where  A0101='");
                    sqlBuf.append(listAll.get(n).get("A0101"));
                    sqlBuf.append("'");
                    if (listAll.get(n).get("A0105") != null) {
                        sqlBuf.append(" and A0105='");
                        sqlBuf.append(listAll.get(n).get("A0105"));
                        sqlBuf.append("'");
                    }
                    if (listAll.get(n).get("A0106") != null) {
                        sqlBuf.append(" and datetime(A0106)==datetime('");
                        sqlBuf.append(listAll.get(n).get("A0106"));
                        sqlBuf.append("')");
                    }
                    ResultSet rs1 = stmt1.executeQuery(sqlBuf.toString());
                    ResultSetMetaData rsm = rs1.getMetaData();
                    sqlBuf.delete(0, sqlBuf.length());
                    if (insertStr1 == null || insertStr2 == null || preSQL == null || insertArr == null) {
                        insertStr1 = getColumnNameStr("A01", createTableMap, rsm);
                        insertStr2 = getInsert2(insertStr1);
                        insertArr = insertStr1.split(",");
                        preSQL = "INSERT INTO A01 (" + insertStr1 + ")values (" + insertStr2 + ")";
                    }
                    PreparedStatement stmtInsert = oracleConn.prepareStatement(preSQL);
                    stmtInsert.setQueryTimeout(720);
                    while (rs1.next()) {
                        String newid = GenerateUUID.getUUID();
                        seedMess("开始接收>>" + rs1.getString("A0101") + ">>人员信息", toUserId);
                        for (int i = 0; i < insertArr.length; i++) {
                            if (insertArr[i].equals("FLOWID")) {
                                oldId = rs1.getString(insertArr[i]);
                                stmtInsert.setString(i + 1, newid);
                            } else {
                                if (createTableSql == null) {
                                    createTableSql = getcreateSql(createTableMap, "A01");
                                }
                                if (map == null) {
                                    map = getTablesType(oracleConn, list_table_names);
                                }
                                if (MapA01 == null) {
                                    map = getTablesType(oracleConn, list_table_names);
                                    MapA01 = map.get("A01");
                                }
                                handStatementA01(i, insertArr, createTableSql, rs1, stmtInsert, MapA01);
                            }
                        }
                        stmtInsert.execute();
                        list_table_names.remove("A01");
                        seedMess("接收>>" + rs1.getString("A0101") + ">>相关表数据", toUserId);
                        for (int i2 = 0; i2 < list_table_names.size(); i2++) {
                            String tableName = list_table_names.get(i2);
                            Map<String, String> MapA02 = map.get(tableName.toUpperCase());
                            String createTableSql2 = getcreateSql(createTableMap, tableName.toUpperCase());
                            ResultSet rs = stmt2.executeQuery("select * from " + tableName + " where PERSONID='" + oldId + "'");
                            ResultSetMetaData rsm2 = rs.getMetaData();
                            insertStr1 = getColumnNameStr(tableName.toUpperCase(), createTableMap, rsm2);
                            insertStr2 = getInsert2(insertStr1);
                            PreparedStatement st2 = oracleConn.prepareStatement("INSERT INTO " + tableName + "(" + insertStr1 + ")values (" + insertStr2 + ")");
                            st2.setQueryTimeout(720);
                            while (rs.next()) {
                                String flowid = GenerateUUID.getUUID();
                                for (int k = 1; k <= rsm2.getColumnCount(); k++) {
                                    if (rsm2.getColumnName(k).toUpperCase().equals("FLOWID")) {
                                        oldId = rs.getString(rsm2.getColumnName(k));
                                        st2.setString(k, flowid);
                                    } else if (rsm2.getColumnName(k).toUpperCase().equals("PERSONID")) {
                                        oldId = rs.getString(rsm2.getColumnName(k));
                                        st2.setString(k, newid);
                                    } else {
                                        if (createTableSql2 == null) {
                                            createTableSql2 = getcreateSql(createTableMap, tableName.toUpperCase());
                                        }
                                        if (map == null) {
                                            map = getTablesType(oracleConn, list_table_names);
                                        }
                                        if (MapA02 == null) {
                                            map = getTablesType(oracleConn, list_table_names);
                                            MapA02 = map.get(tableName.toUpperCase());
                                        }
                                        handStatementA01Tables(k, rsm2, createTableSql2, rs, st2, MapA02);
                                    }
                                }
                                st2.execute();
                            }
                            st2.close();
                        }
                    }
                    stmt1.close();
                    stmt2.close();
                    stmtInsert.close();
                }
            }
            sqlliteConn.close();
            oracleConn.close();
            seedMess("插入人员表数据>>结束", toUserId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private Map<String, Map<String, String>> getTablesType(Connection oracleConn, List<String> list_table_names) {
        HashMap<String, Map<String, String>> tableSqlMap = new HashMap<>();
        try {
            Statement pstate2 = oracleConn.createStatement();
            for (int i = 0; i < list_table_names.size(); i++) {
                Map<String, String> map = new HashMap<>();
                ResultSet check = pstate2.executeQuery("SELECT column_name, data_type FROM all_tab_cols WHERE table_name = '" + list_table_names.get(i).toUpperCase() + "'");
                while (check.next()) {
                    map.put(check.getString(1), check.getString(2));
                }
                tableSqlMap.put(list_table_names.get(i).toUpperCase(), map);
            }
            pstate2.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tableSqlMap;
    }

    private void insertBunit(String dbPath, String toUserId) {
        DataSource drs = this.jdbcTemplate.getDataSource();
        String[] tableArry = this.streamconfig.getBtables().split(",");
        List<String> list_table_names_b = new ArrayList<>();
        Collections.addAll(list_table_names_b, tableArry);
        list_table_names_b.add("B01");
        try {
            Connection oracleConn = drs.getConnection();
            Connection sqlliteConn = new J4SqlLiteUtils().getConnection(dbPath);
            seedMess("获取单位相关所有建表语句>>开始", toUserId);
            Map<String, String> createTableMap = getCreateTableSql(oracleConn, list_table_names_b);
            seedMess("获取单位相关所有建表语句>>结束", toUserId);
            Statement stmt1 = sqlliteConn.createStatement();
            Statement stmt2 = sqlliteConn.createStatement();
            ResultSet rs2 = stmt1.executeQuery("select * from B01");
            ResultSetMetaData rsm = rs2.getMetaData();
            String insertStr1 = getColumnNameStr("B01", createTableMap, rsm);
            PreparedStatement stmtInsert = oracleConn.prepareStatement("INSERT INTO B01 (" + insertStr1 + ")values (" + getInsert2(insertStr1) + ")");
            stmtInsert.setQueryTimeout(720);
            String createTableSql = getcreateSql(createTableMap, "B01");
            String oldId = null;
            seedMess("插入单位表数据>>开始", toUserId);
            while (rs2.next()) {
                String newid = GenerateUUID.getUUID();
                seedMess("插入单位" + rs2.getString("B0101"), toUserId);
                for (int i = 1; i <= rsm.getColumnCount(); i++) {
                    if (rsm.getColumnName(i).toUpperCase().equals("FLOWID")) {
                        oldId = rs2.getString(rsm.getColumnName(i));
                        stmtInsert.setString(i, newid);
                    } else {
                        handStatement(i, rsm, createTableSql, rs2, stmtInsert);
                    }
                }
                stmtInsert.execute();
                list_table_names_b.remove("B01");
                for (int i2 = 0; i2 < list_table_names_b.size(); i2++) {
                    String tableName = list_table_names_b.get(i2);
                    String createTableSql2 = getcreateSql(createTableMap, tableName);
                    ResultSet rs = stmt2.executeQuery("select * from " + tableName + " where UNITID='" + oldId + "'");
                    ResultSetMetaData rsm2 = rs.getMetaData();
                    String insertStr12 = getColumnNameStr(tableName, createTableMap, rsm2);
                    PreparedStatement st2 = oracleConn.prepareStatement("INSERT INTO " + tableName + "(" + insertStr12 + ")values (" + getInsert2(insertStr12) + ")");
                    st2.setQueryTimeout(720);
                    while (rs.next()) {
                        String flowid = GenerateUUID.getUUID();
                        for (int k = 1; k <= rsm2.getColumnCount(); k++) {
                            if (rsm.getColumnName(k).toUpperCase().equals("FLOWID")) {
                                oldId = rs.getString(rsm2.getColumnName(k));
                                st2.setString(k, flowid);
                            } else if (rsm.getColumnName(k).toUpperCase().equals("UNITID")) {
                                oldId = rs.getString(rsm2.getColumnName(k));
                                st2.setString(k, newid);
                            } else {
                                handStatement(k, rsm2, createTableSql2, rs, st2);
                            }
                        }
                        st2.execute();
                    }
                    st2.close();
                }
            }
            stmt1.close();
            stmt2.close();
            sqlliteConn.close();
            stmtInsert.close();
            oracleConn.close();
            seedMess("插入单位表数据>>结束", toUserId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void handStatementA01(int i, String[] insertArr, String createTableSql, ResultSet rs2, PreparedStatement stmtInsert, Map<String, String> mapA01) {
        try {
            String cKey = insertArr[i];
            String cKey1 = insertArr[i].toLowerCase();
            String cKey2 = insertArr[i].toUpperCase();
            int n = i + 2;
            if (createTableSql.contains(cKey) || createTableSql.contains(cKey1) || createTableSql.contains(cKey2)) {
                if (rs2.getObject(n) == null) {
                    if (mapA01.get(cKey2).equals("DATE")) {
                        stmtInsert.setNull(i + 1, 93);
                    } else {
                        stmtInsert.setNull(i + 1, 1);
                    }
                    int i2 = i + 1;
                } else if (mapA01.get(cKey2).equals("VARCHAR2")) {
                    stmtInsert.setString(i + 1, String.valueOf(rs2.getObject(n)).replace("'", "").replace("\"", ""));
                    int i3 = i + 1;
                } else if (mapA01.get(cKey2).equals("BLOB")) {
                    stmtInsert.setBytes(i + 1, rs2.getBytes(n));
                    int i4 = i + 1;
                } else if (mapA01.get(cKey2).equals("DATE")) {
                    String result = String.valueOf(rs2.getObject(n));
                    if (result.length() > 19) {
                        result = result.substring(0, 19);
                    }
                    if (isDateTime(result)) {
                        stmtInsert.setTimestamp(i + 1, new Timestamp(DateUtil.stringtoDate(result, "yyyy-MM-dd HH:mm:ss").getTime()));
                    } else {
                        stmtInsert.setNull(i + 1, 93);
                    }
                    int i5 = i + 1;
                } else {
                    stmtInsert.setString(i + 1, String.valueOf(rs2.getObject(n)));
                    int i6 = i + 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handStatementA01Tables(int i, ResultSetMetaData rsm, String createTableSql, ResultSet rs2, PreparedStatement stmtInsert, Map<String, String> mapA01) {
        try {
            String cKey = rsm.getColumnName(i);
            String cKey1 = rsm.getColumnName(i).toLowerCase();
            String cKey2 = rsm.getColumnName(i).toUpperCase();
            if (createTableSql.contains(cKey) || createTableSql.contains(cKey1) || createTableSql.contains(cKey2)) {
                if (rs2.getObject(i) == null) {
                    if (mapA01.get(cKey2).equals("DATE")) {
                        stmtInsert.setNull(i, 93);
                    } else {
                        stmtInsert.setNull(i, 1);
                    }
                    int i2 = i + 1;
                } else if (mapA01.get(cKey2).equals("VARCHAR2")) {
                    stmtInsert.setString(i, String.valueOf(rs2.getObject(i)).replace("'", "").replace("\"", ""));
                    int i3 = i + 1;
                } else if (mapA01.get(cKey2).equals("BLOB")) {
                    Blob b1 = rs2.getBlob(i);
                    stmtInsert.setBytes(i, b1.getBytes(1, (int) b1.length()));
                    int i4 = i + 1;
                } else if (mapA01.get(cKey2).equals("DATE")) {
                    String result = String.valueOf(rs2.getObject(i));
                    if (result.length() > 19) {
                        result = result.substring(0, 19);
                    }
                    if (isDateTime(result)) {
                        stmtInsert.setTimestamp(i, new Timestamp(DateUtil.stringtoDate(result, "yyyy-MM-dd HH:mm:ss").getTime()));
                    } else {
                        stmtInsert.setNull(i, 93);
                    }
                    int i5 = i + 1;
                } else {
                    stmtInsert.setString(i, String.valueOf(rs2.getObject(i)));
                    int i6 = i + 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handStatement(int i, ResultSetMetaData rsm, String createTableSql, ResultSet rs2, PreparedStatement stmtInsert) {
        try {
            String cKey = rsm.getColumnName(i);
            String cKey1 = rsm.getColumnName(i).toLowerCase();
            String cKey2 = rsm.getColumnName(i).toUpperCase();
            if (createTableSql.contains(cKey) || createTableSql.contains(cKey1) || createTableSql.contains(cKey2)) {
                if (rs2.getObject(i) == null) {
                    stmtInsert.setNull(i, 1);
                    int i2 = i + 1;
                } else if (rs2.getObject(i).getClass().getName().equals("java.lang.String")) {
                    stmtInsert.setString(i, String.valueOf(rs2.getObject(i)).replace("'", "").replace("\"", ""));
                    int i3 = i + 1;
                } else if (String.valueOf(rs2.getObject(i)).contains("oracle.sql.BLOB")) {
                    Blob b1 = (Blob) rs2.getObject(i);
                    stmtInsert.setBytes(i, b1.getBytes(1, (int) b1.length()));
                    int i4 = i + 1;
                } else {
                    stmtInsert.setString(i, String.valueOf(rs2.getObject(i)));
                    int i5 = i + 1;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getInsert2(String insertStr1) {
        String[] arr = insertStr1.split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            sb.append("?,");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    private String getColumnNameStr(String tableName, Map<String, String> createTableMap, ResultSetMetaData rsm) throws SQLException {
        String str = getcreateSql(createTableMap, tableName);
        StringBuilder sb = new StringBuilder();
        for (int n = 1; n <= rsm.getColumnCount(); n++) {
            try {
                String cKey = rsm.getColumnName(n);
                String cKey1 = rsm.getColumnName(n).toLowerCase();
                String cKey2 = rsm.getColumnName(n).toUpperCase();
                if (str.contains(cKey) || str.contains(cKey1) || str.contains(cKey2)) {
                    sb.append(rsm.getColumnName(n));
                    sb.append(",");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    private String getcreateSql(Map<String, String> createTableMap, String string) {
        String sql = null;
        for (String key : createTableMap.keySet()) {
            if (key.equals(string)) {
                sql = createTableMap.get(key);
            }
        }
        return sql;
    }

    private Map<String, String> getCreateTableSql(Connection oracleConn, List<String> list_table_names) {
        HashMap<String, String> tableSqlMap = new HashMap<>();
        try {
            Statement pstate2 = oracleConn.createStatement();
            for (int i = 0; i < list_table_names.size(); i++) {
                ResultSet check = pstate2.executeQuery("select dbms_metadata.get_ddl('TABLE','" + list_table_names.get(i).toUpperCase() + "') from dual");
                while (check.next()) {
                    tableSqlMap.put(list_table_names.get(i).toUpperCase(), check.getString(1));
                }
            }
            pstate2.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return tableSqlMap;
    }

    private void deleteRepeatData(List<Map<String, Object>> list, Connection conn, String dbType) {
        try {
            Statement stmt = conn.createStatement();
            String[] tableArry = this.streamconfig.getTables().split(",");
            List<String> list_table_names = new ArrayList<>();
            Collections.addAll(list_table_names, tableArry);
            for (int i = 0; i < list.size(); i++) {
                StringBuffer sql = new StringBuffer("select flowid from A01 where 1=1 ");
                for (Map.Entry<String, Object> entry : list.get(i).entrySet()) {
                    if (entry.getValue() != null) {
                        if (!entry.getKey().equals("A0106")) {
                            sql.append(" and " + entry.getKey() + "='" + entry.getValue().toString() + "'");
                        } else if (dbType.equals("oracle")) {
                            sql.append(" and A0106 = to_date('" + entry.getValue().toString() + "','yyyy-MM-dd HH24:mi:ss')");
                        } else if (dbType.equals("sqllite")) {
                            sql.append(" and datetime(A0106)==datetime('" + entry.getValue().toString() + "')");
                        }
                    }
                }
                ResultSet rs2 = stmt.executeQuery(sql.toString());
                rs2.setFetchSize(10000);
                String personid = "";
                while (rs2.next()) {
                    personid = rs2.getString(1);
                }
                if (!personid.equals("") && personid.length() > 1) {
                    stmt.executeUpdate("delete from A01 where flowid='" + personid + "'");
                    for (int n = 0; n < list_table_names.size(); n++) {
                        stmt.executeUpdate("delete from " + list_table_names.get(i) + "where PERSONID='" + personid + "'");
                    }
                }
                rs2.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void sourceDateHandle(String type, String unitid, String importUnitid, String connpath, String toUserId) {
        Connection sqlliteConn = new J4SqlLiteUtils().getConnection(connpath);
        try {
            sqlliteConn.setAutoCommit(false);
            if (type.equals("0")) {
                seedMess("预处理数据一>>新增>>处理单位相关", toUserId);
                getDeptTreeList(queryDetpIdList(importUnitid, sqlliteConn), sqlliteConn);
                updatePid(sqlliteConn, unitid, importUnitid);
            } else if (type.equals("1")) {
                List<String> childList = queryDetpIdList(importUnitid, sqlliteConn);
                seedMess("预处理数据一>覆盖>>处理单位相关", toUserId);
                getDeptTreeList(childList, sqlliteConn);
                updatePid(sqlliteConn, ((B01) this.b01Mapper.selectById(unitid)).getParentid(), importUnitid);
            }
            sqlliteConn.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updatePid(Connection sqlliteConn2, String pid, String id) {
        if (pid != null && id != null) {
            String sql = "UPDATE B01 set parentid= '" + pid + "' WHERE flowid = '" + id + "'";
            try {
                Statement stmt = sqlliteConn2.createStatement();
                stmt.execute(sql);
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void updateid(Connection sqlliteConn, String oldid, String newid) {
        if (newid != null && oldid != null) {
            String sql = ("UPDATE B01 set flowid= '" + newid + "' ") + "WHERE flowid = '" + oldid + "'";
            try {
                Statement st = sqlliteConn.createStatement();
                Statement st2 = sqlliteConn.createStatement();
                st.execute(sql);
                String[] tableArry = this.streamconfig.getBtables().split(",");
                List<String> list_table_names_b = new ArrayList<>();
                Collections.addAll(list_table_names_b, tableArry);
                for (int i = 0; i < list_table_names_b.size(); i++) {
                    st2.execute("update " + list_table_names_b.get(i) + " set UNITID='" + newid + "' where UNITID='" + oldid + "'");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void updateA1915(Connection sqlliteConn, String oldid, String newid) {
        if (newid != null && oldid != null) {
            try {
                sqlliteConn.createStatement().execute(("UPDATE A19 set A1915= '" + newid + "' ") + "WHERE A1915 = '" + oldid + "'");
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private void getDeptTreeList(List<String> subIdList, Connection sqlliteConn) {
        for (String deptId : subIdList) {
            List<String> list = queryDetpIdList(deptId, sqlliteConn);
            if (list.size() > 0) {
                getDeptTreeList(list, sqlliteConn);
            }
            String nowid = GenerateUUID.getUUID();
            updateid(sqlliteConn, deptId, nowid);
            updateA1915(sqlliteConn, deptId, nowid);
        }
    }

    public List<String> queryDetpIdList(String parentId, Connection sqlliteConn) {
        List<String> list = new ArrayList<>();
        try {
            ResultSet rs = sqlliteConn.createStatement().executeQuery("select flowid from B01 where PARENTID='" + parentId + "'");
            rs.setFetchSize(10000);
            while (rs.next()) {
                list.add(rs.getString(1));
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    private void seedMess(String mess, String toUserId) {
        try {
            WebSocketServer.sendInfo(mess, toUserId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override // com.tdqy.cadre.modular.profess.service.DataStreamService
    public R outStreamList(Map<String, String> params) {
        if (params.get("unitid").trim().equals("")) {
            return R.ok().put("mess", (Object) "未选择单位");
        }
        this.b01Mapper.selectChildUnits(params.get("unitid"));
        return R.ok().put("list", (Object) this.b01Mapper.outStreamList(params));
    }

    public static String readTxt(String txtPath) {
        File file = new File(txtPath);
        if (!file.isFile() || !file.exists()) {
            return null;
        }
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            StringBuffer sb = new StringBuffer();
            while (true) {
                String text = bufferedReader.readLine();
                if (text == null) {
                    return sb.toString();
                }
                sb.append(text + "\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void test() throws Exception {
    }

    public static boolean isDateTime(String date) {
        StringBuffer reg = new StringBuffer("^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])");
        reg.append("-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]");
        reg.append("|[13579][26])00)-02-29)\\s+([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$");
        return Pattern.compile(reg.toString()).matcher(date).matches();
    }
}
